"""
  Created by Amor on 2018-08-20
"""
from django.db.models.signals import pre_delete, pre_save
from django.dispatch import receiver

from .models import ShoppingCart

__author__ = '骆杨'


@receiver(pre_save, sender=ShoppingCart)
def create_userfav(sender, instance=None, **kwargs):
    existed_record = ShoppingCart.objects.filter(id=instance.id).first()
    if existed_record:
        existed_nums = existed_record.nums
        nums = existed_nums - instance.nums
        goods = instance.goods
        goods.goods_num += nums
        goods.save()
    else:
        goods = instance.goods
        goods.goods_num -= instance.nums
        goods.save()


@receiver(pre_delete, sender=ShoppingCart)
def delete_userfav(sender, instance=None, created=False, **kwargs):
    goods = instance.goods
    goods.fav_num += instance.nums
    goods.save()
